// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const collection = db.collection('bubble_tags')
const _ = db.command
const MAX_LIMIT = 100

// 云函数入口函数
exports.main = async (event, context) => {
    // 获取字段名和默认值
    const { fieldName, defaultValue } = event

    if (!fieldName) {
        return {
            success: false,
            message: '请提供要添加的字段名'
        }
    }

    try {
        // 1. 获取集合中的总记录数
        const countResult = await collection.count()
        const total = countResult.total

        // 2. 计算需要分几次取
        const batchTimes = Math.ceil(total / MAX_LIMIT)

        // 3. 批量更新数据
        let successCount = 0
        let failCount = 0

        for (let i = 0; i < batchTimes; i++) {
            // 3.1 获取当前批次的数据
            const list = await collection.skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()

            // 3.2 批量更新
            const tasks = list.data.map(item => {
                // 如果该记录已经有这个字段，则跳过
                if (item[fieldName] !== undefined) {
                    return Promise.resolve({
                        skipped: true,
                        id: item._id
                    })
                }

                // 构建更新对象
                const updateData = {}
                updateData[fieldName] = defaultValue

                // 更新记录
                return collection.doc(item._id).update({
                    data: updateData
                }).then(() => {
                    successCount++
                    return {
                        success: true,
                        id: item._id
                    }
                }).catch(err => {
                    failCount++
                    return {
                        success: false,
                        id: item._id,
                        error: err
                    }
                })
            })

            // 等待所有更新完成
            await Promise.all(tasks)
        }

        return {
            success: true,
            total,
            successCount,
            failCount,
            message: `成功为${successCount}条记录添加字段 ${fieldName}`
        }

    } catch (err) {
        console.error('批量添加字段失败', err)
        return {
            success: false,
            error: err,
            message: '批量添加字段失败'
        }
    }
}